package com.school.zhaoban.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.school.zhaoban.response.CommonResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author 又菜又爱玩
 * @version 1.0
 * @date 2022/2/19 20:58
 * @blog https://blog.csdn.net/biancheng4/article/details/121727982
 */
@RestControllerAdvice(basePackages = {"com.school.zhaoban.controller"})
public class CommonResponseAdvice implements ResponseBodyAdvice {

    public static final Logger log = LoggerFactory.getLogger(CommonResponseAdvice.class);

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        log.info("进入全局组装统一返回========================");

        return !returnType.getGenericParameterType().equals(CommonResponse.class);
    }


    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        String returnClassType = returnType.getParameterType().getSimpleName();
        log.info("进入组装+++++++++++++++++++++++++++++++:" + returnClassType);

        // String类型不能直接包装，所以要进行些特别的处理
        if (returnType.getGenericParameterType().equals(String.class)) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                // 将数据包装在ResultVO里后，再转换为json字符串响应给前端
                return objectMapper.writeValueAsString(CommonResponse.ok(objectMapper));
            } catch (JsonProcessingException e) {
                throw new BusinessException(201, e.getMessage());
            }
        }
        // 将原本的数据包装在ResultVO里
        return CommonResponse.ok(body);
    }
}
